import 'package:common_utils/common_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:psi/theme/app_colors.dart';
import 'package:psi/utils/utils.dart';
import 'package:psi/utils/widget_util.dart';
import 'package:psi/widgets/app_bar.dart';
import 'package:psi/widgets/empty_widget.dart';
import 'package:psi/widgets/gesture.dart';
import 'package:psi/widgets/text_widget.dart';

import '../../../generated/assets.dart';
import 'purchase_logic.dart';

class PurchasePage extends StatelessWidget {
  final logic = Get.put(PurchaseLogic());
  final state = Get
      .find<PurchaseLogic>()
      .state;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: "采购",
        showBack: false,
        leading: ClickWidget(
          onTap: logic.showSearch,
          child: Container(
            width: 24,
            height: 24,
            child: Icon(
              Icons.search,
              color: Colors.white,
              size: 24,
            ),
          ),
        ),
        actions: [
          IconButton(
              onPressed: logic.addAction,
              icon: Icon(
                Icons.add,
                color: Colors.white,
                size: 28,
              ))
        ],
      ),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.all(8),
            color: primaryColor.withOpacity(0.5),
            child: Row(
              children: [
                Expanded(
                  child: GetBuilder<PurchaseLogic>(
                      id: "statistics",
                      builder: (logic) {
                        return Row(
                          children: [
                            Expanded(
                              child: Column(
                                children: [
                                  WidgetUtil.getStatisticsItem(title: "订单总金额", value: "￥ ${Utils.getFormatStepCount(amount: state.statisticsData.value.totalAmount)}"),
                                  4.verticalSpace,
                                  WidgetUtil.getStatisticsItem(title: "已支付金额", value: "￥ ${Utils.getFormatStepCount(amount: state.statisticsData.value.payedAmount)}"),
                                  4.verticalSpace,
                                  WidgetUtil.getStatisticsItem(title: "待支付金额", value: "￥ ${Utils.getFormatStepCount(amount: state.statisticsData.value.noPayAmount)}"),
                                ],
                              ),
                            ),
                            16.horizontalSpace,
                            Expanded(
                              child: Column(
                                children: [
                                  WidgetUtil.getStatisticsItem(title: "订单总数", value: "${state.statisticsData.value.totalCount}"),
                                  4.verticalSpace,
                                  WidgetUtil.getStatisticsItem(title: "结清订单数", value: "${state.statisticsData.value.payedCount}"),
                                  4.verticalSpace,
                                  WidgetUtil.getStatisticsItem(title: "未结清订单数", value: "${state.statisticsData.value.noPayCount}"),
                                ],
                              ),
                            ),
                          ],
                        );
                      }),
                ),
              ],
            ),
          ),
          Obx(() {
            return state.showSearch.value
                ? GetBuilder<PurchaseLogic>(
                id: "search",
                builder: (logic) {
              return Container(
                padding: EdgeInsets.all(8),
                color: Colors.white,
                child: Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                            child: GetBuilder<PurchaseLogic>(
                                id: "startTime",
                                builder: (logic) {
                                  return WidgetUtil.pickTimeWidget(
                                      title: "开始时间",
                                      showTitle: false,
                                      value: DateUtil.getDateTime(state.search.value.startTime ?? ''),
                                      onDone: (dateTime) {
                                        state.search.value.startTime = DateUtil.formatDate(dateTime, format: DateFormats.full);
                                        logic.update(["startTime"]);
                                      });
                                })),
                        8.horizontalSpace,
                        TextWidget("至"),
                        8.horizontalSpace,
                        Expanded(
                            child: GetBuilder<PurchaseLogic>(
                                id: "endTime",
                                builder: (logic) {
                                  return WidgetUtil.pickTimeWidget(
                                      title: "结束时间",
                                      showTitle: false,
                                      value: DateUtil.getDateTime(state.search.value.endTime ?? ''),
                                      onDone: (dateTime) {
                                        state.search.value.endTime = DateUtil.formatDate(dateTime, format: DateFormats.full);
                                        logic.update(["endTime"]);
                                      });
                                })),
                      ],
                    ),
                    8.verticalSpace,
                    Row(
                      children: [
                        Expanded(
                            child: GetBuilder<PurchaseLogic>(
                                id: "settlementType",
                                builder: (logic) {
                                  return WidgetUtil.pickWidget(
                                      title: "类型",
                                      value: state.settlementTypeList[state.search.value.settlementType!.toInt()],
                                      dataSource: state.settlementTypeList,
                                      showTitle: false,
                                      onDone: (value) {
                                        state.search.value.settlementType = state.settlementTypeList.indexOf(value);
                                        logic.update(["settlementType"]);
                                      });
                                })),
                        8.horizontalSpace,
                        WidgetUtil.getCardItem(
                          onTap: logic.clearSearch,
                          color: Color(0xD5CC9301),
                          padding: EdgeInsets.symmetric(horizontal: 16),
                          child: Container(
                              height: 40,
                              alignment: Alignment.center,
                              child: TextWidget(
                                "重置",
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              )),
                        ),
                        8.horizontalSpace,
                        WidgetUtil.getCardItem(
                          onTap: () {
                            logic.getData(showLoad: true);
                          },
                          color: primaryColor,
                          padding: EdgeInsets.symmetric(horizontal: 16),
                          child: Container(
                              height: 40,
                              alignment: Alignment.center,
                              child: TextWidget(
                                "搜索",
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              )),
                        ),
                      ],
                    )
                  ],
                ),
              );
            })
                : Container(
              color: Colors.blue,
            );
          }),
          Expanded(
              child: EasyRefresh(
                onRefresh: () async {
                  await logic.getData(pageNumber: 1);
                },
                onLoad: () async {
                  await logic.getData(pageNumber: state.search.value.pageNumber! + 1);
                },
                controller: logic.refreshController,
                child: GetBuilder<PurchaseLogic>(
                    id: "dataSource",
                    builder: (logic) {
                      return state.dataSource.value == null || state.dataSource.value.records == null || state.dataSource.value.records!.isEmpty
                          ? EmptyWidget("暂无数据")
                          : SingleChildScrollView(
                        child: Column(
                          children: [
                            8.verticalSpace,
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 8.w),
                              child: WidgetUtil.listViewWithSeparated(
                                  children: state.dataSource.value.records!.map((e) {
                                    return Slidable(
                                      startActionPane: e.fullPay ? ActionPane(
                                        extentRatio: 0.3,
                                        motion: ScrollMotion(),
                                        children: [
                                          CustomSlidableAction(
                                            padding: EdgeInsets.zero,
                                            onPressed: (ctx) => logic.unsettlementOrder(e),
                                            backgroundColor: Colors.red,
                                            child: WidgetUtil.assetImage(R.iconUnSettlement, color: Colors.white, size: 80),
                                          ),
                                        ],
                                      ) : null,
                                      endActionPane: e.fullPay ? null : ActionPane(
                                        extentRatio: 0.3,
                                        motion: ScrollMotion(),
                                        children: [
                                          CustomSlidableAction(
                                            padding: EdgeInsets.zero,
                                            onPressed: (ctx) => logic.settlementOrder(e),
                                            backgroundColor: Colors.blue,
                                            child: WidgetUtil.assetImage(R.iconSettlement, color: Colors.white, size: 80),
                                          ),
                                        ],
                                      ),
                                      child: Stack(
                                        children: [
                                          WidgetUtil.getCardItem(
                                            onTap: () => logic.checkDetail(e),
                                              radius: BorderRadius.all(Radius.circular(16)),
                                              padding: EdgeInsets.all(16),
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  TextWidget(
                                                    e.recordTime,
                                                    fontSize: 16,
                                                  ),
                                                  8.verticalSpace,
                                                  TextWidget(
                                                    e.stockUserName,
                                                    fontSize: 16,
                                                    color: Color(0xFF333333),
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                  8.verticalSpace,
                                                  Row(
                                                    children: [
                                                      ClickWidget(
                                                          onTap: () => logic.callPhone(e.stockPhone),
                                                          child: TextWidget(
                                                            e.stockPhone ?? "未填写",
                                                            fontSize: 16,
                                                            color: primaryColor,
                                                          )),
                                                    ],
                                                  ),
                                                  8.verticalSpace,
                                                  WidgetUtil.divider,
                                                  8.verticalSpace,
                                                  WidgetUtil.listViewWithSeparated(
                                                      children: e.itemList!.map((item) {
                                                        return Container(
                                                          child: Column(
                                                            crossAxisAlignment: CrossAxisAlignment.start,
                                                            children: [
                                                              Row(
                                                                children: [
                                                                  Expanded(
                                                                    child: TextWidget(
                                                                      item.name,
                                                                      fontSize: 14,
                                                                      color: Color(0xFFE87D02),
                                                                    ),
                                                                  ),
                                                                  Expanded(
                                                                    child: TextWidget(
                                                                      "总计：￥${Utils.getFormatStepCount(amount: (item.count ?? 0) * (item.price ?? 0))}",
                                                                      fontSize: 14,
                                                                      color: Colors.red,
                                                                    ),
                                                                  ),
                                                                ],
                                                              ),
                                                              8.verticalSpace,
                                                              Row(
                                                                children: [
                                                                  Expanded(
                                                                    child: TextWidget(
                                                                      "规格：${item.standards ?? "未填写"}",
                                                                      fontSize: 14,
                                                                      color: Color(0xFF666666),
                                                                    ),
                                                                  ),
                                                                  Expanded(
                                                                    child: TextWidget(
                                                                      "尺寸：${item.size ?? "未填写"}",
                                                                      fontSize: 14,
                                                                      color: Color(0xFF666666),
                                                                    ),
                                                                  ),
                                                                ],
                                                              ),
                                                              4.verticalSpace,
                                                              Row(
                                                                children: [
                                                                  Expanded(
                                                                    child: TextWidget(
                                                                      "数量：${item.count ?? "未填写"}",
                                                                      fontSize: 14,
                                                                      color: Color(0xFF666666),
                                                                    ),
                                                                  ),
                                                                  Expanded(
                                                                    child: TextWidget(
                                                                      "单价：${item.price == null ? "未填写" : Utils.getFormatStepCount(amount: item.price)}",
                                                                      fontSize: 14,
                                                                      color: Color(0xFF666666),
                                                                    ),
                                                                  ),
                                                                ],
                                                              ),
                                                              4.verticalSpace,
                                                              Row(
                                                                children: [
                                                                  Expanded(
                                                                    child: TextWidget(
                                                                      "材质：${item.material ?? "未填写"}",
                                                                      fontSize: 14,
                                                                      color: Color(0xFF666666),
                                                                    ),
                                                                  ),
                                                                  Spacer(),
                                                                ],
                                                              ),
                                                            ],
                                                          ),
                                                        );
                                                      }).toList(),
                                                      separator: Container(
                                                        height: 14.h,
                                                        alignment: Alignment.center,
                                                        child: WidgetUtil.divider,
                                                      )),
                                                  8.verticalSpace,
                                                  WidgetUtil.divider,
                                                  8.verticalSpace,
                                                  Row(
                                                    children: [
                                                      Expanded(
                                                          child: Row(
                                                            children: [
                                                              TextWidget("已支付："),
                                                              TextWidget(
                                                                "￥${Utils.getFormatStepCount(amount: e.payAmount)}",
                                                                fontSize: 14,
                                                                color: Colors.red,
                                                                fontWeight: FontWeight.bold,
                                                              ),
                                                            ],
                                                          )),
                                                      Expanded(
                                                          child: Row(
                                                            children: [
                                                              TextWidget("待支付："),
                                                              TextWidget(
                                                                "￥${Utils.getFormatStepCount(amount: e.realAmount! - e.payAmount!)}",
                                                                fontSize: 14,
                                                                color: Colors.red,
                                                                fontWeight: FontWeight.bold,
                                                              ),
                                                            ],
                                                          )),
                                                    ],
                                                  ),
                                                  8.verticalSpace,
                                                  Row(
                                                    children: [
                                                      Spacer(),
                                                      Expanded(
                                                          child: Row(
                                                            children: [
                                                              TextWidget("总金额："),
                                                              TextWidget(
                                                                "￥${Utils.getFormatStepCount(amount: e.realAmount)}",
                                                                fontSize: 14,
                                                                color: Colors.red,
                                                                fontWeight: FontWeight.bold,
                                                              ),
                                                            ],
                                                          ))
                                                    ],
                                                  ),
                                                ],
                                              )),
                                          Positioned(right: 0, top: 0, child: WidgetUtil.assetImage(e.fullPay ? R.settlement : R.noSettlement, size: 70))
                                        ],
                                      ),
                                    );
                                  }).toList(),
                                  height: 8.h),
                            ),
                            8.verticalSpace
                          ],
                        ),
                      );
                    }),
              ))
        ],
      ),
    );
  }
}
